//
//  TaskCreationViewController.m
//  MemoryTasks
//
//  Created by Philippe Bouamriou on 12/05/10.
//  Copyright 2010 Philippe Bouamriou. All rights reserved.
//

#import "CategoryEditionViewController.h"
#import "CategoriesViewController.h"
#import "MemoryTasksAppDelegate.h"
#import "Category.h"


@implementation CategoryEditionViewController


@synthesize navController, modeCategoryController;
@synthesize categoryToModify, parentCategory;


 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
   if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
      // Custom initialization
      modeCategoryController = NSModeCategoryControllerCreation;
   }
   return self;
}



// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
   appDelegate = [[UIApplication sharedApplication] delegate];
   
   UIBarButtonItem *barButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemDone 
                                                            target:self action:@selector(doneButtonPressed)];
   
   self.navigationItem.rightBarButtonItem=barButtonItem;
   doneButton = barButtonItem;
   doneButton.enabled = NO;
   
   sections = [[NSMutableDictionary alloc] init];
   
   UITextField *textField = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 290, 25)];
   textField.tag = kNameTextFieldTag;
   textField.returnKeyType = UIReturnKeyDone;
   [textField addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
   [textField addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
   if (categoryToModify) {
      textField.text = categoryToModify.name;
      if ([categoryToModify.name length]) {
         doneButton.enabled = YES;
      }
   }
   [sections setValue:textField forKey:kFieldTextNameKey];
   
   textField = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 290, 25)];
   textField.tag = kCommentTextFieldTag;
   textField.returnKeyType = UIReturnKeyDone;
   [textField addTarget:self action:@selector(textFieldValueChanged:) forControlEvents:UIControlEventEditingChanged];
   [textField addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
   if (categoryToModify) textField.text = categoryToModify.comment;
   [sections setValue:textField forKey:kFieldTextCommentKey];
   
   sectionNames = [sections allKeys];
   
   NSMutableArray *locals = [[NSMutableArray alloc] init];
   
   for(NSString *sectionName in sectionNames) {
      if( [sectionName isEqualToString:kFieldTextNameKey] )
         [locals addObject:NSLocalizedString(@"Name :", @"Name edition label")];
      else if( [sectionName isEqualToString:kFieldTextCommentKey] )
         [locals addObject:NSLocalizedString(@"Comment :", @"Comment edition label")];
      else [locals addObject:NSLocalizedString(@"Unknown section :", @"Error text if no section localized")];
   }
   
   localSectionNames = [locals copy];
   
   if (categoryToModify) {
      self.title = categoryToModify.name;
      if (parentCategory) {
         self.navigationItem.prompt = NSLocalizedString(@"Sub Category Edition", @"View title for sub category edition");
      }
      else {
         self.navigationItem.prompt = NSLocalizedString(@"Category Edition", @"View title for category edition");
      }
   } else {
      if (parentCategory) {
         self.title = NSLocalizedString(@"S.Cat. Creation", @"View title for sub category creation");
      }
      else {
         self.title = NSLocalizedString(@"Cat. Creation", @"View title for category creation");
      }
   }

   
   [super viewDidLoad];
}

/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
   [super viewDidUnload];
   // Release any retained subviews of the main view.
   // e.g. self.myOutlet = nil;
   self.navController = nil;
   doneButton = nil;
   sections = nil;
   sectionNames = nil;
   localSectionNames = nil;
}



#pragma mark -
#pragma mark Acccessors and Mutators not synthesized

- (void) setCategoryToModify:(TaskCategory*)category {
   modeCategoryController = NSModeCategoryControllerEdition;
   if (categoryToModify != category) {
      categoryToModify = category;
   }
   
   UITextField *textField = [sections valueForKey:kFieldTextNameKey];
   textField.text = categoryToModify.name;
   
   textField = [sections valueForKey:kFieldTextCommentKey];
   textField.text = categoryToModify.comment;
}

#pragma mark -
#pragma mark Custom Methods

- (void)doneButtonPressed {
   NSManagedObjectContext *context = [appDelegate managedObjectContext];
   
   if (modeCategoryController == NSModeCategoryControllerCreation) {
      TaskCategory *category = [NSEntityDescription insertNewObjectForEntityForName:@"Category" inManagedObjectContext:context];
      
      if (category != nil) {
         UITextField *textField = [sections valueForKey:kFieldTextNameKey];
         [textField resignFirstResponder];
         category.name = textField.text;
         
         textField = [sections valueForKey:kFieldTextCommentKey];
         [textField resignFirstResponder];
         category.comment = textField.text;
         
         category.parentCategory = parentCategory;
         
         NSError *error;
         
         [context save:&error];
      }
      
   } else {
      UITextField *textField = [sections valueForKey:kFieldTextNameKey];
      [textField resignFirstResponder];
      categoryToModify.name = textField.text;
      
      textField = [sections valueForKey:kFieldTextCommentKey];
      [textField resignFirstResponder];
      categoryToModify.comment = textField.text;
      
      categoryToModify.parentCategory = parentCategory;
      
      NSError *error;
      
      [context save:&error];
   }
   
   [navController popViewControllerAnimated:YES];
   
   NSArray *allControllers = [navController viewControllers];
   CategoriesViewController *parent = [allControllers lastObject];
   [parent reloadData];   
}

- (void)textFieldValueChanged:(id)sender {
   UITextField *textField = sender;
   if (textField.tag == kNameTextFieldTag && [textField.text length] > 0 ) {
      doneButton.enabled = YES;
   }
   else if (textField.tag == kNameTextFieldTag && [textField.text length] == 0) {
      doneButton.enabled = NO;
   }
}

- (void)textFieldDone:(id)sender {
   [sender resignFirstResponder];
}

#pragma mark -
#pragma mark Implementation of protocol UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
   return [localSectionNames count];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
   return 1;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
   return [localSectionNames objectAtIndex:section];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
   static NSString *MyCell = @"MyCell";
   
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyCell];
   
   if (cell == nil) {
      cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyCell];
   }
   
   [cell.contentView addSubview:[sections valueForKey:[sectionNames objectAtIndex:[indexPath section]]]];
   cell.selectionStyle = UITableViewCellSelectionStyleNone;
   
   return cell;   
}

#pragma mark -
#pragma mark Implementation of protocol UITableViewDelegate

- (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath {
   
   UITextField *textField = [sections valueForKey:[sectionNames objectAtIndex:indexPath.section]];
   [textField becomeFirstResponder];
   return nil;
}


@end
